package com.campusbook.service.impl;

import com.campusbook.dao.UserDao;
import com.campusbook.model.User;
import com.campusbook.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户服务实现类
 * 演示Bean生命周期回调
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    
    @Autowired
    private UserDao userDao;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * Bean初始化回调
     */
    @PostConstruct
    public void init() {
        logger.info("=== UserServiceImpl Bean初始化完成 ===");
    }

    /**
     * Bean销毁回调
     */
    @PreDestroy
    public void destroy() {
        logger.info("=== UserServiceImpl Bean销毁 ===");
    }

    @Override
    @Cacheable(value = "users", key = "#id")
    public User findById(Long id) {
        logger.info("查询用户ID: {}", id);
        return userDao.findById(id);
    }

    @Override
    @Cacheable(value = "users", key = "#username")
    public User findByUsername(String username) {
        logger.info("查询用户名: {}", username);
        return userDao.findByUsername(username);
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public void save(User user) {
        logger.info("保存用户: {}", user.getUsername());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userDao.save(user);
    }

    @Override
    public void update(User user) {
        logger.info("更新用户: {}", user.getUsername());
        if (user.getPassword() != null && !user.getPassword().startsWith("$2a$")) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        userDao.update(user);
    }

    @Override
    public void delete(Long id) {
        logger.info("删除用户ID: {}", id);
        userDao.delete(id);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userDao.countByUsername(username) > 0;
    }

    @Override
    public boolean existsByEmail(String email) {
        return userDao.countByEmail(email) > 0;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(),
            user.getPassword(),
            user.getStatus() == 1,
            true,
            true,
            true,
            Collections.singletonList(new org.springframework.security.core.authority.SimpleGrantedAuthority("ROLE_" + user.getRole()))
        );
    }
}
